package com.winchain.provider;

import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.winchain.basic.exception.ExtException;
import com.winchain.chainbill.risk.utill.RateUtil;
import com.winchain.provider.expiration.po.CbDebit;
import com.winchain.provider.expiration.po.CbDebitIns;
import com.winchain.provider.expiration.service.CbDebitInsService;
import com.winchain.provider.expiration.service.CbDebitService;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExpDebitInsProvider {
	@Autowired
	private CbDebitService cbDebitService;
	@Autowired
	private CbDebitInsService cbDebitInsService;

	@RequestMapping({ "/billExpiration/debitIns" })
	public void expDebitInsBatchJob(@RequestParam("date") String date) {
		String theDayBefore;
		try {
			theDayBefore = DateUtil.getPreDay(date, -1);
		} catch (ParseException e) {
			throw new ExtException("��������������");
		}
		BigDecimal overdueRate = null;
		Map<String, BigDecimal> debitRateMap = new HashMap();

		List<CbDebit> debits = this.cbDebitService.selectOverdueDebit(theDayBefore);
		for (CbDebit debit : debits) {
			overdueRate = getOverduceRate(debit.getBillId(), debitRateMap);

			CbDebitIns debitIns = this.cbDebitInsService.selectByDebitId(debit.getDebitId());
			if (debitIns == null) {
				debitIns = new CbDebitIns();
				debitIns.setInsId(SystemUtil.getUUID());
				debitIns.setDebitId(debit.getDebitId());
				debitIns.setBillAmt(debit.getBillAmount());
				debitIns.setInsDate(date);
				debitIns.setOverdueRate(overdueRate);
				debitIns.setOverdueState("0");
				debitIns.setCreateTime(DateUtil.getSystemDateTime());
				this.cbDebitInsService.save(debitIns);
			}
		}
	}

	private BigDecimal getOverduceRate(String billId, Map<String, BigDecimal> debitRateMap) {
		BigDecimal rate = (BigDecimal) debitRateMap.get(billId);
		if (rate == null) {
			String rateStr = RateUtil.getOverdueRateByBillId(billId, "overdue_rate", "4");
			if (StringUtil.emptyAndNull(rateStr)) {
				throw new ExtException("��������������");
			}
			rate = new BigDecimal(rateStr);
			debitRateMap.put(billId, rate);
		}
		return rate;
	}
}
